<template>
  <view style="padding: 0 32rpx;">
    <!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
    <up-form labelPosition="left" labelWidth="75" :model="formData" :rules="rules" ref="formRef">
      <up-form-item label="门店名称" prop="name" borderBottom required>
        <up-input v-model="formData.name" border="none" placeholder="请填写门店名称"></up-input>
      </up-form-item>
      <up-form-item label="门店简称" prop="short_name" borderBottom>
        <up-input v-model="formData.short_name" border="none" placeholder="请填写门店简称"></up-input>
      </up-form-item>
      <up-form-item label="联系人" prop="contact" borderBottom required>
        <up-input v-model="formData.contact" border="none" placeholder="请填写门店联系人"></up-input>
      </up-form-item>
      <up-form-item label="联系电话" prop="phone" borderBottom required>
        <up-input v-model="formData.phone" border="none" placeholder="请填写门店联系电话"></up-input>
      </up-form-item>
      <up-form-item label="地址" prop="address" borderBottom required @click="setAddress">
        <up-input v-model="formData.address" border="none" placeholder="点击选择门店地址" readonly></up-input>
      </up-form-item>
      <up-form-item label="店面图片" prop="logo" borderBottom>
        <up-upload :fileList="fileList1" :previewFullImage="true" maxCount="3" @afterRead="addImage" @delete="delImage" multiple></up-upload>
      </up-form-item>
    </up-form>
    <up-button @click="submit" type="primary" :loading="submitLoading" :disabled="submitLoading">提交</up-button>
    <up-notify ref="NotifyRef"></up-notify>
  </view>
</template>

<script setup lang="ts">
  import { ref, reactive } from 'vue';
  import { useNotify } from '@/hooks/web/useNotify/index.js'
  import { storeCreate } from '@/api/home'
  
  // 消息弹窗
  const NotifyRef = ref<any>(null)
  const { showNotify } = useNotify(NotifyRef)
  
  const formData = ref({
    name: '',
    short_name: '',
    contact: '',
    phone: '',
    address: '',
    region_id: '',
    lon: '',
    lat: '',
    logo: ''
  })
  const rules = reactive({
    'name': {
      type: 'string',
      required: true,
      message: '请填写门店名称',
      trigger: ['blur', 'change'],
    },
    'contact': {
      type: 'string',
      required: true,
      message: '请填写门店联系人',
      trigger: ['blur', 'change'],
    },
    'phone': {
      type: 'string',
      required: true,
      message: '请填写门店联系电话',
      trigger: ['blur', 'change'],
    },
    'address': {
      type: 'string',
      required: true,
      message: '请填写门店地址',
      trigger: ['blur', 'change'],
    }
  })

  // 使用 ref 创建响应式引用  
  const formRef = ref(null);
  
  const useUploadImg = () => {
  	const fileList1 = ref<any[]>([])
  
  	// 添加图片
  	type UploadImageFile = {
  		size : number,
  		type : 'image',
  		url : string,
  		thumb : string
  	}
  	type UploadImageParams = {
  		file : UploadImageFile | UploadImageFile[],
  		index : number,
  		name : string
  	}
  	type AddImage = (event : UploadImageParams) => any
  	// 新增图片
  	const addImage = async (event) => {
  		// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
  		let lists = [].concat(event.file);
  		let fileListLen = fileList1.value.length;
  		lists.map((item) => {
  			fileList1.value.push({
  				...item,
  				status: 'uploading',
  				message: '上传中',
  			});
  		});
  		for (let i = 0; i < lists.length; i++) {
  			const result = await uploadImage(lists[i].url);
  			let item = fileList1.value[fileListLen];
  			fileList1.value.splice(fileListLen, 1, {
  				...item,
  				status: 'success',
  				message: '',
  				url: result,
  			});
  			fileListLen++;
  		}
  	};
  
  	const uploadImage = (url) => {
  		return new Promise((resolve, reject) => {
  			let a = uni.uploadFile({
  				url: `${process.env.VUE_APP_BASE_URL}/mini/driver/upload`,
  				filePath: url,
  				name: 'file',
  				header: {
  					'content-type': 'application/json;charset=utf-8',
  					'token': uni.getStorageSync('trioToken'),
  				},
  				success: (res) => {
  					const data = JSON.parse(res.data)
  					if (data.code !== 200) {
  						uni.showToast({
  							title: `${data.msg},请重新上传!`,
  							icon: 'none'
  						})
  						return
  					}
  					setTimeout(() => {
  						resolve(data.data.url);
  					}, 1000);
  				},
  			});
  		});
  	};
  	// 删除图片
  	const delImage = (event : UploadImageParams) => {
  		fileList1.value.splice(event.index, 1)
  	}
  
  	return {
  		fileList1,
  		addImage,
  		delImage,
  		uploadImage
  	}
  }
  const { fileList1, addImage, delImage } = useUploadImg()
  
  // 选择地址
  const setAddress = () => {
    uni.chooseLocation({
      success: (res) => {
        if (res) {
          formData.value.address = `${res.address}${res.name}`
          formData.value.lon = res.longitude
          formData.value.lat = res.latitude
        }
      },
      fail: (err) => {
        console.log(err);
      }
    })
  }
  
  const submitLoading = ref(false)
  const submit = async () => {
    if (fileList1.value.length > 0) {
      formData.value.logo = fileList1.value.map((item) => item.url).join(',')
    }
    formRef.value.validate().then(async() => {
      try {
        submitLoading.value = true
        const res = await storeCreate(formData.value)
        showNotify({
          type: 'success',
          message: res.msg,
          top: 0
        })
        formRef.value.resetFields()
        fileList1.value = []
      } catch (error) {
        showNotify({
        	type: 'error',
        	message: error.msg,
          top: 0
        })
      } finally {
        submitLoading.value = false
      }
    })
    
  }
</script>

<style>
</style>